package com.hy.mybatisplus.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.dao.DataAccessException;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import com.hy.mybatisplus.config.PageDto;
import com.hy.mybatisplus.config.SearchRequest;
import com.hy.mybatisplus.entity.R;
import com.hy.mybatisplus.entity.PeopleEntity;
import com.hy.mybatisplus.service.data.PeopleDataService;
import com.hy.mybatisplus.request.PeopleEntityRequest;


/**
 * 描述:
 * author: hy
 * date: 2020-09-28
 */
@Service
public class PeopleService {
    @Autowired
    private PeopleDataService dataService;

    @Transactional(rollbackFor = DataAccessException.class)
    public R insert(PeopleEntityRequest request) {
        PeopleEntity entity = new PeopleEntity();
        BeanUtils.copyProperties(request, entity);
        return dataService.save(entity) ? R.ok() : R.error();
    }

    /**
     * 在 mybatis plus3.X 中 去除了updateAllColumn方法，如果要更新所有字段，让前端传这个字段，字段值置空就可以了
     * @param request
     * @return
     */
    @Transactional(rollbackFor = DataAccessException.class)
    public R updateById(PeopleEntityRequest request) {
        PeopleEntity entity = new PeopleEntity();
        BeanUtils.copyProperties(request, entity);
        return dataService.updateById(entity) ? R.ok() : R.error();
    }

    public R findById(String id) {
        return R.ok().putData("entity", dataService.getById(id));
    }

    public R deleteById(String id) {
        return dataService.removeById(id) ? R.ok() : R.error();
    }

    public R searchPage(PeopleEntityRequest request, PageDto<PeopleEntity> pageDto, SearchRequest<PeopleEntity> searchRequest) {
        QueryWrapper<PeopleEntity> wrapper = request.getEqWrapper();
        searchRequest.covertWrapper(wrapper);
        return R.ok().putData("page", dataService.page(pageDto.getPageUtil(), wrapper));
    }
}
